package util

import (
	"errors"
	"gitee.com/kordar/bucket/model"
	"github.com/kordar/goupload"
	"github.com/kordar/goupload_cos"
	"github.com/kordar/goupload_local"
	"io/fs"
	"path"
	"strings"
)

var uploader = goupload.NewManager()

func GetBucketHandler(bucket model.Bucket) (goupload.BucketUploader, error) {
	if handler := uploader.GetHandler(bucket.Name); handler != nil {
		return handler, nil
	} else {
		return CreateHandler(bucket)
	}
}

func CreateHandler(bucket model.Bucket) (goupload.BucketUploader, error) {
	config := bucket.GetConfig()
	// 初始化本地存储桶
	if bucket.Driver == model.LocalDriver {
		if config["root"] == "" {
			return nil, errors.New("parameter root is required")
		}

		localUploader := goupload_local.NewLocalUploader(config["root"], bucket.Name, func(s string, entry fs.DirEntry) bool {
			base := path.Base(s)
			return strings.HasPrefix(base, ".")
		})
		uploader.Add(localUploader)
		return localUploader, nil
	}

	if bucket.Driver == model.CosDriver {
		var cosClient = goupload_cos.NewCOSClient("www-1257614471", "ap-shanghai", "AKIDMVP3QYR3PYTAcooa7OSHp66pHTO3VhcG", "PYR3PWN2SbT4PTHo56qKUO3SbT4QWLtA")
		uploader.Add(cosClient)
		return cosClient, nil
	}

	return nil, errors.New("driver does not exist")
}
